import Config from '@/settings'
function crud(apiName) {
  return {
    data() {
      return {
        tableData: [], // 列表数据
        page: {
          total: 0, // 总记录数
          current: 1, // 当前页码
          size: 10, // 每页记录数
          orders: [{ column: 'id', asc: true }]
        },
        searchCondition: {
          createTime: [], // 创建时间数组
          keyWord: ''// 关键字
        }
      }
    },
    mounted() {
      this.initTable()
    },
    methods: {
      async initTable(current = 1) {
        const { page, searchCondition } = this
        if (Number.isInteger(current)) {
          page.current = current
        }
        const result = await this.$API[apiName].pageQuery({ searchCondition, page }) // todo
        if (result.code === 200) {
          this.tableData = result.data.records
          this.page.current = result.data.current
          this.page.size = result.data.size
          this.page.total = result.data.total
        }
      },
      resetSearchCondition() {
        this.searchCondition.createTime = []
        this.searchCondition.keyWord = ''
        this.initTable()
      },
      async ezDelete(row) {
        let ids = []
        if (row.id) {
          ids = [row.id]
        } else {
          ids = this.selectedIds
        }
        if (ids.length === 0) {
          this.$message({
            message: '请选择要操作的数据',
            type: 'warning',
            showClose: true,
            duration: Config.duration
          })
          return
        }
        this.$confirm('此操作将永久删除, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(async() => {
            const result = await this.$API[apiName].delete(ids) // todo
            if (result.code === 200) {
              this.$message({
                message: '删除成功',
                type: 'success',
                showClose: true,
                duration: Config.duration
              })
              this.initTable()
            }
          })
          .catch(() => {
            this.$message({
              type: 'info',
              message: '已取消删除'
            })
          })
      },
      /*
          列表选中状态发生改变的监听回调
        */
      handleSelectionChange(selection) {
        this.selectedIds = selection.map((item) => item.id)
      },
      /*
          处理pageSize发生改变的监听回调
          */
      handleSizeChange(pageSize) {
        this.page.size = pageSize
        this.initTable()
      },
      async ezExport() {
        await this.$API[apiName].exportUser(this.selectedIds) // todo
      }
    }}
}

/**
 * 分页
 */
function pagination() {
  return {
    data() {
      return {
        crud: this.crud,
        page: this.crud.page
      }
    }
  }
}
/**
 * 搜索
 */
function searchable() {
  return {
    data() {
      return {
        crud: this.crud,
        searchCondition: this.crud.searchCondition
      }
    }
  }
}
export {
  pagination,
  searchable,
  crud
}
